import * as React from 'react';
import {MapView, AMapSdk, MapType, Marker} from 'react-native-amap3d';
import {SafeAreaView} from 'react-native-safe-area-context';
import {StyleSheet, View, Dimensions, Text, Platform, ScrollView, TouchableOpacity, TextInput,PermissionsAndroid} from 'react-native';
import Icons from 'react-native-vector-icons/AntDesign';
import {init, Geolocation} from 'react-native-amap-geolocation';


import {HeaderTitle} from '../../../../../../componet/settingComponent/HeaderTitle';
import {BottomButton} from '../../../../../../componet/settingComponent/BottomButton';
import {BrLine} from '../../../../../../componet/settingComponent/BrLine';

import axios from 'axios';
import {preventDoubleClick} from '../../../../../../utils/preventDoubleClick';
import {saveSignPlace} from '../../../../../../api/signPlace';
import {Loading} from '../../../../../../utils/Loading';
import {Toast} from '../../../../../../utils/Toast';
PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
]).catch(err=>{
    Toast.showWarning(err.toString())
}).then(res=>{

});

init({
    ios: '1be169e585123b6e68a91d9aa355ae14',
    android: 'fd68d9ef3201d3ba7376ae6f89673904',
}).then(res=>{
}).catch(err=>{
    Toast.showWarning(err)
});
AMapSdk.init(
    Platform.select({
        android: 'fd68d9ef3201d3ba7376ae6f89673904',
        ios: '1be169e585123b6e68a91d9aa355ae14',
    }),
);

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
let mapView: MapView;
export default  class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            signPlaceId: this.props.route.params.signPlaceId == null ? null : this.props.route.params.signPlaceId,
            text: '',
            init: true,
            location: {
                latitude: this.props.route.params.location.latitude == null ? null : this.props.route.params.location.latitude,
                longitude: this.props.route.params.location.longitude == null ? null : this.props.route.params.location.longitude,
            },
            addressName: '',
            pois: [],
        };
    }

    componentDidMount() {
        this.initMap();
    }

    initMap = () => {
        let location = this.state.location;
        console.log(location);
        //没有值时
        if (location.latitude == null) {
            Geolocation.getCurrentPosition(({coords}) => {
                //console.log(coords);
                let {latitude, longitude} = coords;
                location.longitude = longitude.toFixed(6);
                location.latitude = latitude.toFixed(6);
                this.setState({location});
                mapView?.moveCamera(
                    {
                        tilt: 0,
                        bearing: 0,
                        zoom: 16,
                        target: {latitude: parseFloat(location.latitude), longitude: parseFloat(location.longitude)},
                    },
                    1000,
                );
            });

        } else {
            mapView?.moveCamera(
                {
                    tilt: 0,
                    bearing: 0,
                    zoom: 16,
                    target: {latitude: parseFloat(location.latitude), longitude: parseFloat(location.longitude)},
                },
                1000,
            );
        }
        // this.regeo();

    };

    back = () => {
        let route = {
            name: 'signPlace',
            params: {
                title: '打卡地点',
            },
        };
        this.props.navigation.navigate(route);
    };
    goto = (name, params) => {
        const route = {
            name: name,
            params: {
                routePathName: this.props.route.name,
                ...params,
            },

        };
        this.props.navigation.navigate(route);
    };
    set = (latitude, longitude) => {
        let location = {
            latitude: latitude,
            longitude: longitude,
        };
        this.setState({location});
        this.regeo();
    };
    //逆地理编码
    regeo = () => {
        let location = this.state.location.longitude + ',' + this.state.location.latitude;
        let url = `https://restapi.amap.com/v3/geocode/regeo?key=5f0965f76b755e1dda224ba390195a2f&location=${location}&poitype=&radius=1000&extensions=all&batch=false&roadlevel=0`;
        axios.get(url).then(res => {
            let {data} = res;
            console.log(data);
            if (data.status == 1) {
                let addressName = data.regeocode.formatted_address;
                this.setState({addressName});
            }
        }).catch(err => {
                console.log(err);
                alert('调用高德地图api失败');
            },
        );
    };
    //保存地址
    save = () => {
        let SignPlaceEntity = {
            signPlaceId: this.state.signPlaceId,
            placeLatitude: this.state.location.latitude,
            placeLongitude: this.state.location.longitude,
            errorRange: 100,
        };
        Loading.show();
        saveSignPlace(SignPlaceEntity).then(res => {
            Loading.hidden();
            this.goto('signPlace', {title: '打卡地点', location: this.state.location});
        }).catch(err => {
            Loading.hidden();
            Toast.showWarning(err.toString());
        }).finally(()=>{
            Loading.hidden();
        });
    };
    //关键字搜索
    parameters = (text) => {
        let url = `https://restapi.amap.com/v3/place/text?key=5f0965f76b755e1dda224ba390195a2f&keywords=${text}&types=&city=&children=1&offset=20&page=1&extensions=all`;
        axios.get(url).then(res => {
            let {data} = res;
            console.log(data);
            if (data.status == 1) {
                let pois = data.pois;
                this.setState({pois});
            }
        }).catch(err => {
                alert('调用高德地图api失败');
            },
        );
    };
    onChangeText = (text) => {
        this.setState({text});
    };
    test = (text) => {
        alert(text);
    };

    //用作判断是否选择了当前位置
    location() {
        return this.state.location.longitude + ',' + this.state.location.latitude;
    }

    render() {

        return (

            <SafeAreaView edges={['top', 'left', 'right', 'bottom']} style={{flex: 1, backgroundColor: '#ffffff'}}>
                <View style={style.container}>
                    <HeaderTitle goBack={() => this.back()} headtitle={this.props.route.params.title}></HeaderTitle>
                    <View style={{width: width, height: 200}}>
                        <MapView
                            ref={(ref: MapView) => (mapView = ref)}
                            myLocationEnabled={true}
                            onLoad={(nativeEvent) => {
                                console.log(nativeEvent);
                            }}
                            onCameraIdle={({nativeEvent}) => {
                                this.set(nativeEvent.cameraPosition.target.latitude.toFixed(6), nativeEvent.cameraPosition.target.longitude.toFixed(6));
                            }}
                        >
                            <Marker
                                draggable
                                position={{
                                    // latitude: this.state.location.latitude==null?30.720066:this.state.location.latitude,
                                    // longitude: this.state.location.longitude==null?110.6185455:this.state.location.longitude,
                                    latitude: this.state.location.latitude == null ? 0.720066 :parseFloat(this.state.location.latitude) ,
                                    longitude: this.state.location.longitude == null ? 0.6185455 :parseFloat( this.state.location.longitude),
                                }}

                                onPress={() => alert('onPress')}
                                onDragEnd={({nativeEvent}) =>
                                    alert(`onDragEnd: ${nativeEvent.latitude}, ${nativeEvent.longitude}`)
                                }
                            />
                        </MapView>
                    </View>
                    <View style={style.searchCard}>
                        <View style={style.searchCard_top}>
                            <TextInput
                                style={{
                                    width: width - 7 - 7 - 60 - 7,
                                    textAlign: 'left',
                                    borderColor: 'transparent',
                                    backgroundColor: '#eee',
                                    borderRadius: 10,
                                    borderWidth: 1,
                                    padding: 7,
                                    fontSize: 17,
                                }}
                                maxLength={30}
                                placeholder='输入城市名+地名'
                                secureTextEntry={false}
                                onChangeText={text => this.onChangeText(text)}
                                value={this.state.text}
                            />
                            <TouchableOpacity onPress={() => {
                                this.parameters(this.state.text);
                            }} style={{
                                width: 60,
                                marginLeft: 7,
                                alignItems: 'center',
                                justifyContent: 'center',
                                backgroundColor: '#409EFF',
                                borderRadius: 7,
                            }}>
                                <Text style={{color: '#fff'}}>搜索</Text>
                            </TouchableOpacity>
                        </View>
                        <BrLine></BrLine>
                        <ScrollView style={style.searchCard_body}>
                            <TouchableOpacity onPress={() => {
                            }}>
                                <View style={style.body_item}>
                                    <View style={style.addText}>
                                        <Text style={{
                                            fontSize: 16,
                                            color: '#171B1D',
                                            marginBottom: 2,
                                        }}>[位置]</Text>
                                        <Text style={{
                                            fontSize: 12,
                                            color: '#747578',
                                        }}>{this.state.addressName}</Text>
                                    </View>
                                    {
                                        this.state.init == true ?
                                            <Icons name={'check'} style={{color: '#409EFF'}} size={20}/> :
                                            <View></View>
                                    }

                                </View>
                            </TouchableOpacity>
                            <BrLine></BrLine>


                            {this.state.pois.map((item, index) => {
                                return (
                                    <View key={item.id}>
                                        <TouchableOpacity onPress={() => {
                                            let str = item.location;
                                            let ls = str.split(',');
                                            this.set(ls[1], ls[0]);
                                            this.setState({init: false});
                                            mapView?.moveCamera(
                                                {
                                                    tilt: 0,
                                                    bearing: 0,
                                                    zoom: 16,
                                                    target: {latitude: parseFloat(ls[1]), longitude: parseFloat(ls[0])},
                                                },
                                                1000,
                                            );
                                        }}>
                                            <View style={style.body_item}>
                                                <View style={style.addText}>
                                                    <Text style={{
                                                        fontSize: 16,
                                                        color: '#171B1D',
                                                        marginBottom: 2,
                                                    }}>{item.name}</Text>
                                                    <Text style={{
                                                        fontSize: 12,
                                                        color: '#747578',
                                                    }}>{item.pname + item.adname + item.address}</Text>
                                                </View>

                                                {
                                                    item.location == this.location() ?
                                                        <Icons name={'check'} style={{color: '#409EFF'}} size={20}/> :
                                                        <View></View>
                                                }
                                            </View>
                                        </TouchableOpacity>
                                        <BrLine></BrLine>
                                    </View>
                                );
                            })}


                        </ScrollView>
                    </View>
                </View>
                <BottomButton title={'确认'} click={() => {
                    this.save();

                }}></BottomButton>
            </SafeAreaView>
        );
    }

}


const style = StyleSheet.create({
    //样式
    container: {
        backgroundColor: '#F1F0F5',
        flex: 1,
    },
    searchCard: {},
    searchCard_top: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 7,
        width: width,
        backgroundColor: '#fff',

    },
    searchCard_body: {
        height: height - 400,
        paddingLeft: 7,
        backgroundColor: '#fff',
    },
    body_item: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingTop: 7,
        paddingRight: 7,
        paddingBottom: 7,
    },
    addText: {},
});
